"""
网络图Graph：

由节点、边、权重所组成的数据关系图
直观的展示事物节点间的复杂关系
"""

import pandas as pd
from pyecharts import options as opts
from pyecharts.charts import Graph, Page

# 1. 读取足球赛队员传球数据集
dataset = pd.read_csv('./Files/passingevents.csv')
# print(dataset.head())

# 只取一个场次，一个队伍的数据
dataset = dataset[(dataset['MatchID'] == 1) & (dataset['TeamID'] == "Huskies")]
# print(dataset.head())

# 汇总计算，每个球员给其它球员传了多少次球
dataset = dataset.groupby(['OriginPlayerID', 'DestinationPlayerID']).size().reset_index(name='Size')
# print(dataset.head())

# 2. 构造Graph所需的nodes、links数据
# 所有去重后的队员ID
players = pd.concat([dataset["OriginPlayerID"], dataset["DestinationPlayerID"]]).unique()
# print(players)

# 图所需的节点列表
nodes = []
for player in players:
    nodes.append({"name": player, "symbolSize": 10})
# print(nodes)

# 图所需要的边
links = []
for index, row in dataset.iterrows():
    links.append({"source": row["OriginPlayerID"],
                  "target": row["DestinationPlayerID"],
                  "value": row["Size"]})
# print(links)

# 3. 使用Pyecharts绘制Graph图
graph = (
    Graph()
    .add(
        "Passing Network",
        nodes,
        links,
        repulsion=10000,
        edge_label=opts.LabelOpts(is_show=True, position="middle", formatter="{c}"),
    )
    .set_global_opts(title_opts=opts.TitleOpts(title="传球网络图"))
)

graph.render('./Files/my_graph.html')
